package com.weifly.weistock.trade.trade.tradeX;

import com.sun.jna.Native;
import com.sun.jna.ptr.ShortByReference;
import com.weifly.weistock.core.common.StockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 市场行情会话
 *
 * @author weifly
 * @since 2021/6/8
 */
public class TradeXMarketSession {

    private Logger log = LoggerFactory.getLogger(TradeXMarketSession.class);
    private TradeXSessionFactory sessionFactory; // 会话Factory
    private int hqCode; // 行情连接代码

    public TradeXMarketSession(TradeXSessionFactory sessionFactory, int hqCode) {
        this.sessionFactory = sessionFactory;
        this.hqCode = hqCode;
    }

    /**
     * 关闭会话
     */
    public void close() {
        this.sessionFactory.disconnectMarket(this.hqCode);
    }

    public void getDayKLine(String stockCode, int start, int count) {
        byte[] result = new byte[1024 * 1024]; // 调用返回结果
        byte[] errInfo = new byte[256]; // 调用出错信息

        boolean opsSuccess = this.sessionFactory.tdxLibrary().TdxHq_GetSecurityBars(
                this.hqCode,
                (byte) 4,
                (byte) 1,
                stockCode,
                (short) start,
                new ShortByReference((byte) count),
                result,
                errInfo
        );
        if (!opsSuccess) {
            String msg = "获取K线数据出错！原因是: " + Native.toString(errInfo, "GBK");
            throw new StockException(msg);
        }

        String resultStr = Native.toString(result, "GBK");
        if (resultStr == null || resultStr.isEmpty()) {
            log.info("没有查询到K线数据");
            return;
        }

        log.info(resultStr);
    }
}
